package com.daftv.springboot_test02.controller;

import com.daftv.springboot_test02.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

@Controller
public class MyController {

    @GetMapping(value = {"/", "/login"})
    public String login() {
        return "user/login";
    }

    @PostMapping("/userLogin")
    public String userLogin(Model model, User user, HttpSession session) {
        if (user.getUserName().equals("qwe") && user.getPassword().equals("123")) {
            session.setAttribute("loginUser", user);
            return "redirect:main";
        } else {
            if (session.getAttribute("msg") != null) {
                model.addAttribute("msg", session.getAttribute("msg"));
            } else {
                model.addAttribute("msg", "账号密码错误");
            }
            return "user/login";
        }

    }

    @GetMapping("/main")
    public String userMain(Model model, HttpSession session) {
        User user = (User) session.getAttribute("loginUser");
        model.addAttribute("userName", user.getUserName());
        model.addAttribute("password", user.getPassword());
        return "main";
    }

    @RequestMapping("/userLogout")
    public String userLogout(HttpSession session) {
        session.removeAttribute("loginUser");
        return "user/login";
    }
}
